Skip to content

Fix flaky test_csv_to_json in Beam YAML SDK#38617

Open
shunping wants to merge 2 commits into
apache:masterfrom
shunping:fix-test-csv-to-json
Open

Fix flaky test_csv_to_json in Beam YAML SDK#38617
shunping wants to merge 2 commits into
apache:masterfrom
shunping:fix-test-csv-to-json

Conversation

@shunping
Copy link
Copy Markdown
Collaborator

@shunping shunping commented May 24, 2026

The log below is from https://github.com/apache/beam/actions/runs/26350925447/job/77568997003?pr=38612

=================================== FAILURES ===================================
____________________ YamlTransformE2ETest.test_csv_to_json _____________________
[gw3] linux -- Python 3.11.15 /runner/_work/beam/beam/sdks/python/test-suites/tox/py311/build/srcs/sdks/python/target/.tox-py311/py311/bin/python

self = <apache_beam.yaml.yaml_transform_test.YamlTransformE2ETest testMethod=test_csv_to_json>

    def test_csv_to_json(self):
      try:
        import pandas as pd
      except ImportError:
        raise unittest.SkipTest('Pandas not available.')
    
      with tempfile.TemporaryDirectory() as tmpdir:
        data = pd.DataFrame([{'label': f'{i}a', 'rank': i} for i in range(1024)])
    
        input = os.path.join(tmpdir, 'input.csv')
        output = os.path.join(tmpdir, 'output.json')
        data.to_csv(input, index=False)
        with open(input, 'r') as f:
          lines = f.readlines()
        _LOGGER.debug("input.csv has these {lines} lines.")
        self.assertEqual(len(lines), len(data) + 1)  # +1 for header
    
        with beam.Pipeline() as p:
          result = p | YamlTransform(
              '''
              type: chain
              transforms:
                - type: ReadFromCsv
                  config:
                      path: %s
                - type: WriteToJson
                  config:
                      path: %s
                      num_shards: 1
                - type: LogForTesting
              ''' % (repr(input), repr(output)))
        all_output = list(glob.glob(output + "-*"))
        file_and_size = {f: os.path.getsize(f) for f in all_output}
        self.assertEqual(
            len(all_output),
            1,
            msg=f"Expected 1 shard file, but found {len(all_output)}. "
            f"Files & sizes (bytes): {file_and_size}")
        output_shard = all_output[0]
        result = pd.read_json(
            output_shard, orient='records',
            lines=True).sort_values('rank').reindex()
>       pd.testing.assert_frame_equal(data, result)

apache_beam/yaml/yaml_transform_test.py:291: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
testing.pyx:55: in pandas._libs.testing.assert_almost_equal
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

>   ???
E   AssertionError: DataFrame.index are different
E   
E   DataFrame.index values are different (48.53516 %)
E   [left]:  RangeIndex(start=0, stop=1024, step=1)
E   [right]: Index([  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,
E          ...
E          763, 764, 765, 766, 767, 768, 769, 770, 771, 772],
E         dtype='int64', length=1024)
E   At positional index 527, first diff: 527 != 773

testing.pyx:173: AssertionError

result = pd.read_json(
output_shard, orient='records',
lines=True).sort_values('rank').reindex()
pd.testing.assert_frame_equal(data, result)

In the above code, this result DataFrame is sorted by rank but this preserves the permuted index values. Using .reindex() does not reset the index, causing assert_frame_equal to fail when comparing against the original sequential DataFrame.

Replaced .reindex() with .reset_index(drop=True) to correctly discard the permuted index and reset it to a sequential RangeIndex matching the original input.

shunping added 2 commits May 24, 2026 08:34
Sorting this DataFrame by `rank` preserves the permuted index values.
Using `.reindex()` does not reset the index, causing `assert_frame_equal`
to fail when comparing against the original sequential DataFrame.

Replaced `.reindex()` with `.reset_index(drop=True)` to correctly discard
the permuted index and reset it to a sequential RangeIndex matching the
original input.
@shunping
Copy link
Copy Markdown
Collaborator Author

shunping commented May 25, 2026

r: @derrickaw since this is a follow-up fix of #38367 and #38484

@shunping shunping marked this pull request as ready for review May 25, 2026 21:19
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a flaky test in the Beam YAML SDK. The failure was caused by index mismatches during DataFrame comparison in the test_csv_to_json test, as reindex() was not properly resetting the index after sorting. The fix ensures the index is correctly reset to a sequential range, aligning it with the expected input data structure.

Highlights

  • Test Fix: Updated the test_csv_to_json test case in the Beam YAML SDK to use reset_index(drop=True) instead of reindex() when comparing DataFrames.
  • CI Trigger: Incremented the revision number in beam_PostCommit_Python_Versions.json to trigger the test suite.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request triggers the Python post-commit test suite by incrementing a revision number and fixes a test in yaml_transform_test.py by replacing .reindex() with .reset_index(drop=True) on a pandas DataFrame to properly reset the index after sorting. There are no review comments to address.

@github-actions
Copy link
Copy Markdown
Contributor

ghost commented May 25, 2026

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants